<template>
	<view>
		<view class="list-item upload-img-item">
			<view class="add-img-view" @click="onTakePhoto()">
				<image mode="aspectFill" class="add-img" :src="(imgUrl+'/wx/add-picture.png')"/>
				<view>最多上传{{max}}张图片,仅支持jpg/png格式</view>
			</view>
			<view class="add-img-view" v-if="imageUrls.length > 0">
				<u-overlay :show="show" @click="show = false">
					<view style="height: 100vh;width: 100vw;display: flex;justify-content: center;align-items: center;">
						<image  :src="currentSrc" mode="widthFix" style="width: 100vw;"></image>
					</view>
				</u-overlay>
				<!-- <u-album :urls="imageUrls" @delPicClick="onDelete" :showDelBtn='true'></u-album> -->
					<view v-for="(item, index) in imageUrls" :key="index" class="add-img-view-item">
						<image class="add-item" mode="aspectFill" @click ='imageClick(item)' :src="item"/>
						<image mode="widthFix" class="del-img" :src="(imgUrl+'/wx/delete.png')" @click="onDelete(item)"/>
					</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {formatImgPath} from '../../common/filter.js'

	export default {
		props:{
			images: String,
			imageDatas: {
				type: Array,
				default: [],
			},
			max: {
				type: Number,
				default: 9,
			},
			isData: {
				type: Boolean,
				default: false,
			}
		},
		data() {
			return {
				telent:this.$util.isTenant(), //TENANT租户NOT_YET_TENANT不是租户Notloggedin未登录Admin管理员
				imgUrl:this.$config.BASE_imgUrl,
				imageUrls: [],
				fileNames: [],
				show:false,
				currentSrc:''
			}
		},
		created() {
			if (this.images) {
				let images = this.images.split(";")

				for (let image of images) {
					if (!image) continue;
					this.fileNames.push(image)
					this.imageUrls.push(formatImgPath(image))
				}
			}
			console.log('imageDatas', this.imageDatas)
			if(this.imageDatas.length > 0){
				for(let item of this.imageDatas){
					let base64 = 'data:image/png;base64,' + item
					this.fileNames.push(item)
					this.imageUrls.push(base64)
				}
			}
			console.log('imageUrls:',this.imageUrls)
		},
		methods: {
			close(){
				this.show = false
			},
			onTakePhoto() {
				uni.chooseImage({
				    count: this.max, //默认9
				    sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['camera', 'album'], //从相册选择
				    success: (res) => {
				        console.log(res);
						let num = res.tempFilePaths.length;

						let index = 0;
						for (let urlTemp of res.tempFilePaths) {
							index++;
							if ((this.imageUrls.length+index) > this.max){
								this.$util.toast("最多只能添加" + this.max + "张图片")
								continue;
							}
							if(!this.isData){
								//微信登录时接口名称为wx 账号密码登录时为app
								let apiConnect = ''
								if(this.telent==='TENANT' || this.telent==='NOT_YET_TENANT'){
									apiConnect = 'wx'
								}else{
									apiConnect = 'app'
								}
								// console.log('this.$util.getStorage("loginInfo")',this.$util.getStorage("loginInfo"));
								let url =`${this.$config.BASE_URL}${apiConnect}/mySelf/uploadPicfile?token=${this.$util.getStorage("loginInfo").app.token}`
								// console.warn("url: ", url)
								uni.uploadFile({
								    url: url,     // 后端api接口
								    filePath: urlTemp, // uni.chooseImage函数调用后获取的本地文件路劲
								    name:'file',     //后端通过'file'获取上传的文件对象
								    // formData: this.sendDate,
								    header:{"Content-Type": "multipart/form-data"},
								    success:(res) => {
										console.log(3333,res)
										console.warn("文件上传结果：", res)
										if (res.data){
											res = JSON.parse(res.data);
											if (res.result) {
												this.fileNames.push(res.result)
												this.imageUrls.push(formatImgPath(res.result))
											}
											// uni.request({
											//       url: this.imageUrls[0],
											//       responseType: 'arraybuffer',
											//       success: res => {
											//         const base64 = uni.arrayBufferToBase64(res.data);
											//         this.imageUrl = 'data:image/jpeg;base64,' + base64;
											// 		this.imageUrls.push(this.imageUrl)
											//       },
											//       fail: error => {
											//         console.error('Error:', error);
											//       }
											// });
											console.log('urls',this.imageUrls)
								        }
										num--;
										if (num == 0) {
											this._onChange();
										}
								    }
								});
							}else{
								uni.getFileSystemManager().readFile({
									filePath: urlTemp,
									encoding: 'base64',
									success: response => {
										let base64 = 'data:image/png;base64,' + response.data
										// if(urlTemp.endsWith('jpg')){
										// 	base64 = 'data:image/jpg;base64,' + response.data
										// }
										this.fileNames.push(response.data)
										this.imageUrls.push(base64)
										num--;
										if (num == 0) {
											this._onChange();
										}
									}
								})
							}
						}
				    }
				});
				console.log('imageUrls',this.imageUrls)
			},
			imageClick(item,index) {
				this.show = true
				this.currentSrc = item
				// uni.previewImage({
				// 	// current: index,
				// 	urls: this.imageUrls
				// })
			},
			onDelete(item) {
				console.log('item图片',item)
				this.$util.confirm({
					content: "确实要删除图片？",
					confirmText: "删除"
				}).then(isConfirm => {
					if (isConfirm) {
						if(!this.isData){
							this.$util.post({
								url: "app/mySelf/deletePicfile",
								data: {
									fileNames: item.slice(0,-6)
								}
							}).then(res => {
								console.warn("图片删除结果： ", res)
								this.imageUrls.splice(this.imageUrls.indexOf(item), 1)
								this.fileNames.splice(this.fileNames.indexOf(item), 1)
								this._onChange()
							})
						}else{
							this.imageUrls.splice(this.imageUrls.indexOf(item), 1)
							this.fileNames.splice(this.fileNames.indexOf(item), 1)
							this._onChange()
						}

					}
				})
			},
			_onChange() {
				if(this.isData){
					this.$emit('onChange', this.fileNames)
				}else{
					let fileName = ";";
					for (let item of this.fileNames) {
						fileName += item
						fileName += ";"
					}
					this.$emit('onChange', fileName)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
.list-item {
	display: flex;
	flex-direction: row;
	align-items: center;

	color: #333;
	font-size: 28rpx;
	.add-img {
		width: 120rpx;
		height: 120rpx;
		margin-right: 20rpx;
	}
	.del-img {
		position: absolute;
		top: -15rpx;
		right: -15rpx;
		width: 30rpx;
		height: 30rpx;
	}
}
.upload-img-item {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	.add-img-view {
		display: flex;
		align-items: center;
		flex-direction: row;
		flex-wrap: wrap;
		background-color: #FFFFFF !important;
		color: #999;
		font-size: 24rpx;
		margin-top: 20rpx;

		.add-img-view-item {
			position: relative;
			margin-right: 30rpx;
			margin-top: 10rpx;
			.add-item {
				width: 120rpx;
				height: 120rpx;
			}
		}
	}
}
</style>
